package com.tim.app.ui.activity.person_center;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.application.library.widget.refresh.PtrClassicFrameLayout;
import com.application.library.widget.refresh.PtrDefaultHandler;
import com.application.library.widget.refresh.PtrFrameLayout;
import com.application.library.widget.refresh.PtrHandler;
import com.google.gson.Gson;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_User;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.UserFollowResult;
import com.tim.app.server.result.UserRelationStatedResult;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.activity.some_homepage.SomeoneHomepageActivity;
import com.tim.app.ui.adapter.personal.BlackAdapter;
import com.tim.app.ui.popup.ActionPop;
import com.tim.app.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 黑名单列表
 */
public class BlackListActivity extends BaseActivity implements PtrHandler, LoadMoreHandler, BaseRecyclerAdapter.OnItemClickListener, BaseRecyclerAdapter.OnItemLongClickListener {

    private static final String TAG = "BlackListActivity";

    private ImageView ivBack;
    private TextView tvTitle;

    private PtrClassicFrameLayout refresh_layout;
    private LoadMoreRecycleViewContainer load_more;
    private WrapRecyclerView wrvBlack;
    private EmptyLayout emptyLayout;
    private BlackAdapter adapter;
    private List<UserFollowResult.Res.Data.FollowUser> dataList;

    public static void start(Context context) {
        Intent intent = new Intent(context, BlackListActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onBeforeSetContentLayout() {
        super.onBeforeSetContentLayout();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_black_list;
    }

    @Override
    public void initView() {
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        ivBack = (ImageView) findViewById(R.id.ivBack);
        ivBack.setOnClickListener(this);
        refresh_layout = (PtrClassicFrameLayout) findViewById(R.id.refresh_layout);
        load_more = (LoadMoreRecycleViewContainer) findViewById(R.id.load_more);
        wrvBlack = (WrapRecyclerView) findViewById(R.id.wrvBlack);

        wrvBlack.setOverScrollMode(View.OVER_SCROLL_NEVER);
        refresh_layout.disableWhenHorizontalMove(true);
        refresh_layout.setPtrHandler(this);
        load_more.useDefaultFooter(View.GONE);
        load_more.setAutoLoadMore(true);
        load_more.setLoadMoreHandler(this);

        emptyLayout = new EmptyLayout(this, refresh_layout);
        emptyLayout.setEmptyButtonShow(false);
        emptyLayout.showLoading();
        emptyLayout.setEmptyDrawable(R.drawable.ic_empty_friend);

        if (dataList == null) {
            dataList = new ArrayList<>();
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        wrvBlack.setLayoutManager(layoutManager);

        adapter = new BlackAdapter(this, dataList);
        adapter.setOnItemClickListener(this);
        adapter.setOnItemLongClickListener(this);
        wrvBlack.setAdapter(adapter);
        emptyLayout.setEmptyText("你还没有拉黑任何人", "");

        EventManager.ins().registListener(EventTag.DO_DELETE, eventListener);
    }

    int pageNum = 1;

    @Override
    public void initData() {
        API_User.ins().getBlackList(TAG, pageNum, AppKey.PAGE_SIZE, refreshCallback);
    }

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            refresh_layout.refreshComplete();
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                UserFollowResult result = new Gson().fromJson(resultValue, UserFollowResult.class);
                dataList.clear();
                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                        pageNum = result.getRes().getArraylist().getCurrentPageNo();
                        if (pageNum == result.getRes().getArraylist().getTotalPageCount()) {
                            load_more.loadMoreFinish(false, false);
                        } else {
                            load_more.loadMoreFinish(false, true);
                        }
                    }

                    if (dataList.size() == 0) {
                        emptyLayout.showEmpty();
                    } else {
                        emptyLayout.showContent();
                    }
                } else {
                    emptyLayout.showEmpty();
                }
            } else {
                emptyLayout.showEmptyOrError(errCode);
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                UserFollowResult result = new Gson().fromJson(resultValue, UserFollowResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                        pageNum = result.getRes().getArraylist().getCurrentPageNo();
                        if (pageNum == result.getRes().getArraylist().getTotalPageCount()) {
                            load_more.loadMoreFinish(false, false);
                        } else {
                            load_more.loadMoreFinish(false, true);
                        }
                    }
                }
            } else {
                ToastUtil.showToast(errMsg);
            }

            return false;
        }
    };


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                finish();
                break;
        }
    }

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.DO_DELETE:
                    final int position = (int) dataobj;
                    if (dataList.size() > position) {
                        UserFollowResult.Res.Data.FollowUser user = dataList.get(position);
                        API_User.ins().removeBackList(TAG, user.getUserMsg().getUserId(), new StringResponseCallback() {
                            @Override
                            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                                    dataList.remove(position);
                                    adapter.notifyDataSetChanged();
                                    if (dataList.size() == 0) {
                                        emptyLayout.showEmpty();
                                    }
                                } else {
                                    ToastUtil.showToast(errMsg);
                                }
                                return false;
                            }
                        });
                    }
                    break;
            }
        }
    };

    @Override
    public boolean onItemLongClick(View view, int position, long id) {
        ActionPop actionPop = new ActionPop(this, position);
        actionPop.show(wrvBlack);
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        API_User.ins().getBlackList(TAG, pageNum + 1, AppKey.PAGE_SIZE, moreCallback);
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, wrvBlack, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        initData();
    }

    @Override
    public void onItemClick(View view, int position, long id) {
        UserFollowResult.Res.Data.FollowUser data = dataList.get(position);
        SomeoneHomepageActivity.start(this, data.getUserMsg(), false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventManager.ins().removeListener(EventTag.DO_DELETE, eventListener);
    }

}
